package handler

import (
	"awesomeProject/util"
	"strconv"

	"github.com/gin-gonic/gin"

	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
	"awesomeProject/app/verify"
)

type CasbinHandler struct{}

var casbinSrv service.CasbinSrv

// AddPermissionsForRole 权限分配
func (r CasbinHandler) AddPermissionsForRole(ctx *gin.Context) {
	id := ctx.Param("id")
	rid, _ := strconv.Atoi(id)
	var req request.PermissionIds
	_ = ctx.Bind(&req)
	if err := verify.AddPermissionsForRole(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, casbinSrv.AddPermissionsForRole(uint(rid), req.Checked, util.CurrentLogin(ctx)))
	return
}

// AddRolesForUser 为用户附加角色
func (r CasbinHandler) AddRolesForUser(ctx *gin.Context) {
	id := ctx.Param("id")
	uid, _ := strconv.Atoi(id)
	var req request.RoleIds
	_ = ctx.Bind(&req)
	if err := verify.AddRolesForUser(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, casbinSrv.AddRolesForUser(uint(uid), req.RIdS, util.CurrentLogin(ctx)))
	return
}

// UserRoles 获取用户角色
func (r CasbinHandler) UserRoles(ctx *gin.Context) {
	id := ctx.Param("id")
	uid, _ := strconv.Atoi(id)
	response.Result(ctx, casbinSrv.UserRoles(uint(uid), util.CurrentLogin(ctx)))
	return
}

func (r CasbinHandler) CurrentUserRoles(ctx *gin.Context) {
	response.Result(ctx, casbinSrv.UserRoles(util.CurrentLogin(ctx).ID, util.CurrentLogin(ctx)))
	return
}
